package com.mdinic.blogovi.model;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.roo.addon.dod.RooDataOnDemand;
import org.springframework.stereotype.Component;

@Configurable
@Component
@RooDataOnDemand(entity = Blog.class)
public class BlogDataOnDemand {

    private final Random rnd = new SecureRandom();

    private List<Blog> data;

    public void setBlacklisted(Blog obj, int index) {
        Boolean blacklisted = Boolean.TRUE;
        obj.setBlacklisted(blacklisted);
    }

    public Blog getNewTransientBlog(int index) {
        Blog obj = new Blog();
        setUrl(obj, index);
        obj.setAutoApprove(false);
        obj.setBlacklisted(false);
        return obj;
    }

    public void setUrl(Blog obj, int index) {
        String url = "url_" + index;
        obj.setUrl(url);
    }

    public Blog getSpecificBlog(int index) {
        init();
        if (index < 0) {
            index = 0;
        }
        if (index > (data.size() - 1)) {
            index = data.size() - 1;
        }
        Blog obj = data.get(index);
        Long id = obj.getId();
        return Blog.findBlog(id);
    }

    public Blog getRandomBlog() {
        init();
        Blog obj = data.get(rnd.nextInt(data.size()));
        Long id = obj.getId();
        return Blog.findBlog(id);
    }

    public boolean modifyBlog(Blog obj) {
        return false;
    }

    public void init() {
        int from = 0;
        int to = 10;
        data = Blog.findBlogEntries(from, to);
        if (data == null) {
            throw new IllegalStateException("Find entries implementation for 'Blog' illegally returned null");
        }
        if (!data.isEmpty()) {
            return;
        }

        data = new ArrayList<Blog>();
        for (int i = 0; i < 10; i++) {
            Blog obj = getNewTransientBlog(i);
            try {
                obj.persist();
            } catch (ConstraintViolationException e) {
                StringBuilder msg = new StringBuilder();
                for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); iter.hasNext();) {
                    ConstraintViolation<?> cv = iter.next();
                    msg.append("[").append(cv.getConstraintDescriptor()).append(":").append(cv.getMessage())
                            .append("=").append(cv.getInvalidValue()).append("]");
                }
                throw new RuntimeException(msg.toString(), e);
            }
            obj.flush();
            data.add(obj);
        }
    }

    public void setAutoApprove(Blog obj, int index) {
        Boolean autoApprove = Boolean.TRUE;
        obj.setAutoApprove(autoApprove);
    }
}
